package com.sangeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sangeng.constant.LoginConstants;
import com.sangeng.constant.SystemConstants;
import com.sangeng.constant.enums.AppHttpCodeEnum;
import com.sangeng.domain.core.ResponseResult;
import com.sangeng.domain.entity.LoginUser;
import com.sangeng.domain.entity.Menu;
import com.sangeng.domain.entity.Role;
import com.sangeng.domain.entity.User;
import com.sangeng.domain.vo.*;
import com.sangeng.exception.SystemException;
import com.sangeng.mapper.RoleMapper;
import com.sangeng.mapper.UserMapper;
import com.sangeng.service.BlogLoginService;
import com.sangeng.service.MenuService;
import com.sangeng.service.UserService;
import com.sangeng.utils.BeanUtil;
import com.sangeng.utils.JwtUtil;
import com.sangeng.utils.RedisCache;
import com.sangeng.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuService menuService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public ResponseResult login(User user) {
        return login(user, false);
    }

    @Override
    public ResponseResult login(User user, boolean isBackendLogin) {
        // 认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 判断是否认证通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException(LoginConstants.lOGIN_FAILD_MESSAGE);
        }
        // 获取userId，生成token
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        String userId = principal.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        // 把用户信息存入redis
        if(isBackendLogin){
            redisCache.setCacheObject(LoginConstants.REDIS_ADMIN_LOGIN_KEY_PREFIX + userId, principal);
        }
        else redisCache.setCacheObject(LoginConstants.REDIS_LOGIN_KEY_PREFIX + userId, principal);
        // 把token和userinfo封装成userinfo返回
        LoginInfoVo vo = new LoginInfoVo(jwt, BeanUtil.copyBean(principal.getUser(), UserInfoVo.class));
        AdminUserInfoVo adminVo = new AdminUserInfoVo(jwt);
        if(isBackendLogin) return ResponseResult.okResult(adminVo);
        else return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult logout() {
        return logout(false);
    }

    @Override
    public ResponseResult getInfo() {
        Long userId = SecurityUtils.getUserId();
        GetInfoVo vo = new GetInfoVo();
        // 获取角色信息
        List<Role> roles = userMapper.getRoleByUserId(userId);
        vo.setRoles(roles.stream().map(Role::getRoleKey).collect(Collectors.toSet()).stream().toList());
        // 获取权限信息
        List<Menu> menus = null;
        if(vo.getRoles().contains("admin")){
            LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Menu::getStatus, SystemConstants.MENU_STATUS_NORMAL);
            queryWrapper.in(Menu::getMenuType, SystemConstants.CHILD_MENU, SystemConstants.BUTTON);
            menus = menuService.list(queryWrapper);
        }
        else if(!roles.isEmpty()){
            menus = roleMapper.getMenuByRoleId(roles);
        }
        if (menus != null) {
            vo.setPermissions(menus.stream().map(Menu::getPerms).collect(Collectors.toSet()).stream().toList());
        }
        else vo.setPermissions(new ArrayList<>());
        // 获取用户信息
        vo.setUser(BeanUtil.copyBean(SecurityUtils.getLoginUser().getUser(), UserInfoVo.class));
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult getRouters() {
        // 获取当前用户id
        Long userId = SecurityUtils.getUserId();
        // 获取角色信息
        List<Role> roles = userMapper.getRoleByUserId(userId);
        // 获取当前用户菜单信息
        List<Menu> menus = null;
        if(roles.stream().map(Role::getRoleKey).toList().contains("admin")){
            LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Menu::getStatus, SystemConstants.MENU_STATUS_NORMAL);
            queryWrapper.in(Menu::getMenuType, SystemConstants.MENU, SystemConstants.CHILD_MENU);
            menus = menuService.list(queryWrapper);
        }
        else if(!roles.isEmpty()){
            menus = roleMapper.getMenuByRoleIdExceptF(roles);
        }
        // 构建菜单树
        MenuVo menuVo = new MenuVo();
        menuVo.setMenus(menuService.buildMenus(menus));
        return ResponseResult.okResult(menuVo);
    }

    @Override
    public ResponseResult logout(boolean isBackendLogin) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(loginUser == null){
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(isBackendLogin){
            redisCache.deleteObject(LoginConstants.REDIS_ADMIN_LOGIN_KEY_PREFIX + loginUser.getUser().getId());
        }
        else redisCache.deleteObject(LoginConstants.REDIS_LOGIN_KEY_PREFIX + loginUser.getUser().getId());
        return ResponseResult.okResult();
    }
}
